//
//  WDCheckCell.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2017/2/23.
//  Copyright © 2017年 王笛. All rights reserved.
//

#import "WDCheckCell.h"
#import "WDCheck.h"
#import "WDPhoneAlertView.h"
#import "WDMaterial_List.h"
#import "WDMaterListCell.h"
#import "UILabel+WDChangeLineSpace.h"

#define cellItemW 50
#define cellItemH 37

@interface WDCheckCell () <UICollectionViewDelegate, UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UILabel *introLabel;
@property (weak, nonatomic) IBOutlet UIImageView *topline;
@property (weak, nonatomic) IBOutlet UIImageView *statusView;
@property (weak, nonatomic) IBOutlet UIImageView *bottomLine;
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *auditLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UIView *clickView;
@property (weak, nonatomic) IBOutlet UIButton *descBtn;

/** collectionView */
@property (nonatomic, strong) UICollectionView *collectionView;

@end

static NSString *cellID = @"checkImageCell";

@implementation WDCheckCell

//懒加载collectionView
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        //滚动方向（竖直方向）
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 10;
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        
        _collectionView.scrollEnabled = NO;
        
        _collectionView.delegate = self;
        
        _collectionView.dataSource = self;
        
        UINib *nib = [UINib nibWithNibName:NSStringFromClass([WDMaterListCell class]) bundle:nil];
        
        [_collectionView registerNib:nib forCellWithReuseIdentifier:cellID];
        
        _collectionView.backgroundColor = [UIColor clearColor];
        
        [self.contentView addSubview:_collectionView];
    }
    
    return _collectionView;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    //处理图片拉伸
    UIImage *norImage = [UIImage imageNamed:@"icon_chatBox"];
    CGFloat w = norImage.size.width*0.9;
    CGFloat h = norImage.size.height*0.9;
    UIImage *newImage = [norImage resizableImageWithCapInsets:UIEdgeInsetsMake(h, w, h, w) resizingMode:UIImageResizingModeStretch];
    self.descBtn.userInteractionEnabled = NO;
    [self.descBtn setBackgroundImage:newImage forState:UIControlStateNormal];
    
    self.iconView.layer.masksToBounds = YES;
    self.iconView.layer.cornerRadius = 22;
    
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //点击拨打电话手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    [self.clickView addGestureRecognizer:tap];
    
}

- (void)tap
{
    WDPhoneAlertView *alert = [[WDPhoneAlertView alloc] initWithTitle:self.check.modify_name message:self.check.phone sureBtn:@"呼叫" cancleBtn:@"取消"];
    
    
    __weak typeof (self)weakSelf = self;
    alert.resultIndex = ^(NSInteger index){
        
        NSURL *openURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", weakSelf.check.phone]];
        
        [[UIApplication sharedApplication] openURL:openURL];
        
    };
    
    [alert show];
}

+ (instancetype)checkCellWithTableView:(UITableView *)tableView
{
    static NSString *cellID = @"checkCell";
    
    WDCheckCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil] lastObject];
    }
    
    return cell;
}

-(void)setDataWithModel:(WDCheck *)check index:(NSInteger)index maxIndex:(NSInteger)maxIndex
{
    
    self.introLabel.text = check.modify_des;
    self.statusLabel.text = check.status_value;
    
    if (![check.type intValue]) {
        self.statusLabel.textColor = ColorForRGB(0x6b6b6b);
    } else {
        self.statusLabel.textColor = ColorForRGB(0xfd5722);
    }
    
    [self.iconView sd_setImageWithURL:[NSURL URLWithString:check.image_url] placeholderImage:[UIImage imageNamed:@"defaultIcon"]];
    self.timeLabel.text = check.modify_time;
    self.auditLabel.text = check.modify_name;
    self.phoneLabel.text = check.phone;
    
    [self layoutIfNeeded];
    
    CGRect frame = self.frame;
    
    CGRect newFrame = CGRectMake(frame.origin.x, frame.origin.y, WDScreenW, frame.size.height);
    
    self.frame = newFrame;
    
    [self layoutIfNeeded];
    
    WDLog(@"%f", self.descBtn.frame.size.width);
    
    [self.descBtn layoutIfNeeded];
    
    //说明文字
    if ((![check.reason isEqualToString:@""] && check.reason) && (!check.remark || [check.remark isEqualToString:@""])) {
        
        self.descBtn.hidden = NO;
        
        NSString *str = [NSString stringWithFormat:@"%@\n",check.parent_value];
        NSString *attStr = [NSString stringWithFormat:@"%@%@", str, check.reason];
        //替换字符 把','替换成'\n'
        attStr = [attStr stringByReplacingOccurrencesOfString:@"," withString:@"\n"];
        
        [self.descBtn layoutIfNeeded];
        
        CGSize titleSize= [self sizeWithString:attStr font:[UIFont systemFontOfSize:14] constraintSize:CGSizeMake(self.descBtn.frame.size.width - 60, MAXFLOAT)];
        
        [self.descBtn updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(titleSize.height + 40);
        }];
        
        [self.descBtn layoutIfNeeded];
        
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:attStr];
        
        //文字颜色
        [attrStr addAttribute:NSForegroundColorAttributeName value:ColorForRGB(0x6b6b6b) range:NSMakeRange(0, str.length)];
        
        [attrStr addAttribute:NSForegroundColorAttributeName value:WDNavSeleColor range:NSMakeRange(str.length, check.reason.length)];
        
        //行间距
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:5.0];
        paragraphStyle.alignment = NSTextAlignmentCenter;
        [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attStr length])];
        
        [self.descBtn setAttributedTitle:attrStr forState:UIControlStateNormal];
        
        self.descBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        
        self.descBtn.titleLabel.numberOfLines = 0;
        
        self.descBtn.titleLabel.textAlignment = NSTextAlignmentCenter;

    } else if (([check.reason isEqualToString:@""] || !check.reason) && (check.remark && ![check.remark isEqualToString:@""])) {
        
        self.descBtn.hidden = NO;
        
        NSString *attStr = [NSString stringWithFormat:@"%@",check.remark];
        
        CGSize titleSize = [self sizeWithString:attStr font:[UIFont systemFontOfSize:14.0f] constraintSize:CGSizeMake(self.descBtn.frame.size.width - 60, MAXFLOAT)];
        
        [self.descBtn updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(titleSize.height + 40);
        }];
        
        [self.descBtn layoutIfNeeded];
        
        [self.descBtn setTitle:attStr forState:UIControlStateNormal];
        
        self.descBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        
        [UILabel changeLineSpaceForLabel:self.descBtn.titleLabel WithSpace:5.0];
        
        [self.descBtn setTitleColor:WDNavSeleColor forState:UIControlStateNormal];
        
        self.descBtn.titleLabel.numberOfLines = 0;
        
        self.descBtn.titleLabel.preferredMaxLayoutWidth = self.descBtn.frame.size.width;
        
        [self.descBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
        
        
    } else if (![check.reason isEqualToString:@""] && check.reason && check.remark && ![check.remark isEqualToString:@""]) {
        
        self.descBtn.hidden = NO;
        
        NSString *str = [NSString stringWithFormat:@"%@%@",check.parent_value, @"\n"];
        //替换字符 把','替换成'\n'
        check.reason = [check.reason stringByReplacingOccurrencesOfString:@"," withString:@"\n"];
        NSString *attStr = [NSString stringWithFormat:@"%@%@\n%@", str, check.reason, check.remark];
        
        CGSize titleSize= [self sizeWithString:attStr font:[UIFont systemFontOfSize:14] constraintSize:CGSizeMake(self.descBtn.frame.size.width - 60, MAXFLOAT)];
        
        [self.descBtn updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(titleSize.height + 40);
        }];
        
        [self.descBtn layoutIfNeeded];
        
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:attStr];
        
        //字体颜色
        [attrStr addAttribute:NSForegroundColorAttributeName value:ColorForRGB(0x6b6b6b) range:NSMakeRange(0, str.length)];
        
        [attrStr addAttribute:NSForegroundColorAttributeName value:WDNavSeleColor range:NSMakeRange(str.length, check.reason.length + check.remark.length)];
        
        //行间距
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:5.0];
        paragraphStyle.alignment = NSTextAlignmentCenter;
        [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attStr length])];
        
        [self.descBtn setAttributedTitle:attrStr forState:UIControlStateNormal];
        
        self.descBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        
        self.descBtn.titleLabel.numberOfLines = 0;
        
        [self.descBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
        
    } else
    {
        self.descBtn.hidden = YES;
    }
    
    
    if (index == 0 && index != maxIndex) {   // 第一个
        self.topline.hidden = YES;
        self.statusView.image = [UIImage imageNamed:@"android -xhdp"];
        self.bottomLine.hidden = NO;
    } else if (index == 0 && index == maxIndex) {//只有一个
        
        self.topline.hidden = YES;
        self.statusView.image = [UIImage imageNamed:@"android -xhdp"];
        self.bottomLine.hidden = NO;
        
    } else if (index!= 0 && index == maxIndex) // 最后一个
    {
        self.topline.hidden = NO;
        self.statusView.image = [UIImage imageNamed:@"android -xhdpi copy "];
        self.bottomLine.hidden = YES;
    } else  // 中间内容
    {
        self.topline.hidden = NO;
        self.statusView.image = [UIImage imageNamed:@"android -xhdpi copy "];
        self.bottomLine.hidden = NO;
    }
}

- (void)setCheck:(WDCheck *)check
{
    _check = check;
    
    [self layoutIfNeeded];
    
    [self.descBtn layoutIfNeeded];
    
    if (check.material_list.count){
        
        self.collectionView.hidden = NO;
        
        check.checkCellH = CGRectGetMaxY(self.collectionView.frame) + 20;
        
    } else if (!_descBtn.hidden) {
        
        self.collectionView.hidden = YES;
        
        check.checkCellH = CGRectGetMaxY(self.descBtn.frame) + 20;
        
    } else {
        
        self.collectionView.hidden = YES;
        
        check.checkCellH = CGRectGetMaxY(self.phoneLabel.frame) + 20;
    }
    
}

- (void)setImagesArr:(NSArray *)imagesArr
{
    _imagesArr = imagesArr;
    
    if (imagesArr.count) {
        
        [self layoutIfNeeded];
        
        [self.descBtn layoutIfNeeded];
        
        CGFloat collecX = CGRectGetMinX(self.iconView.frame);
        CGFloat collecY;
        CGFloat collecW = WDScreenW - 20 - CGRectGetMinX(self.iconView.frame);
        CGFloat collecH = (imagesArr.count - 1) / 4 * 14 + ((imagesArr.count - 1) / 4 + 1) * 37;
        
        if (self.descBtn.hidden) {
            
            collecY = CGRectGetMaxY(self.phoneLabel.frame) + 14;
            
            self.collectionView.frame = CGRectMake(collecX, collecY, collecW, collecH);
            
        } else {
            
            collecY = CGRectGetMaxY(self.descBtn.frame) + 20;
            
            self.collectionView.frame = CGRectMake(collecX, collecY, collecW, collecH);
        }
        
        //刷新collectionView
        [self.collectionView reloadData];
    }
    
    
}

#pragma mark - <UICollectionView代理>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.imagesArr.count == 0) {
        
        return 1;
        
    } else {
        
        return self.imagesArr.count;
        
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WDMaterListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    cell.material = self.imagesArr[indexPath.row];
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(cellItemW, cellItemH);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *images = [NSMutableArray array];
    WDMaterial_list *material;
    
    for (material in self.imagesArr) {
        [images addObject:material.big_image_url];
    }
    
    [_delegate checkCellShowOriginalImage:images index:indexPath.row];
    
//    WDLog(@"点击了第%zd个图片", indexPath.row);
}

@end
